<script setup lang="ts" name="video-index">
import {
  defineComponent,
  onMounted,
  onActivated,
  reactive,
  ref,
  toRaw,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  cameraList,
  getIserList,
  getDeptTree,
  getActionList,
  cameraSave,
  delCamera,
  getAllDeptCameraTree,
} from "@/api/server_set_camera";
/* data */
const router = useRouter();
const height = ref(0);
const tempIndex = ref();
const isEdit = ref(false);
const isBig = ref(false);
const dialogVisible_add = ref(false);
const dialogVisible_map = ref(false);

const listParams = ref({
  page: 1,
  pageSize: 20,
});
const List = ref([]);
const total = ref(0);

const deptOptions = ref([]);
const userList = ref<any>([]);
const actionList = ref([]);

const formData = ref<any>({
  dep: [],
  relatedCameraIds: [],
  action_list: [],
  coordinate: "",
});
const cascaderProps = reactive({
  label: "label",
  value: "id",
  children: "children",
  checkStrictly: true,
  emitPath: false,
});
const currentPage = ref(1);

/* methods */
const addItem = () => {
  isEdit.value = false;
  formData.value = {};
  dialogVisible_add.value = true;
};
const edit = (data: any) => {
  isEdit.value = true;
  formData.value = {
    ...data,
  };
  console.log("data", data);

  formData.value.action_list = formData.value.action_list
    ? formData.value.action_list.split(",")
    : [];
  let related_camera_ids = formData.value.related_camera_ids
    ? formData.value.related_camera_ids.split(",")
    : [];
  formData.value.relatedCameraIds = related_camera_ids.map((v: any) => {
    return "camera_" + v;
  });
  dialogVisible_add.value = true;
  setMap();
  
};
const remove = (data: any) => {
  ElMessageBox.confirm(
    `<span>确定要删除 <i style="color:#58B2C5;">${data.camera_name}</i> 吗</span>`,
    "提 示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
      type: "warning",
    }
  ).then(async () => {
    let res = await delCamera({
      id: data.camera_id,
    });
    if (res.result == "success") {
      getList(0);
      ElMessage({
        type: "success",
        message: "删除成功!",
      });
    }
  });
};

const getList = async (page: number) => {
  let res = await cameraList({
    ...toRaw(listParams.value),
    page,
  });
  console.log("摄像头", res);
  if (res.result == "success") {
    List.value = res.list;
    total.value = Number(res.total);
  }
};
const getUser = async () => {
  let res = await getIserList({});
  if (res.result == "success") {
    userList.value = res.list;
  }
};
const getDeptInfo = async () => {
  let res = await getDeptTree({});
  if (res.result == "success") {
    deptOptions.value = res.deptTree;
  }
};
const getActionListInfo = async () => {
  let res = await getActionList({});
  if (res.result == "success") {
    actionList.value = res.actionList;
  }
};

const passwordShow = async (data: any, type: any) => {
  data.passwordShow = type;
};
const handleSizeChange = (val: number) => {
  listParams.value.pageSize = val;
  getList(currentPage.value);
};
const handleCurrentChange = (val: number) => {
  getList(val);
};
const confirmAdd = async () => {
  let res = await cameraSave({
    id: isEdit ? formData.value.camera_id : 0,
    deptId: formData.value.dept_id,
    userId: formData.value.user_id,
    cameraName: formData.value.camera_name,
    ip: formData.value.ip,
    coordinate: formData.value.coordinate,
    userName: formData.value.user_name,
    password: formData.value.password,
    action_list: formData.value.action_list,
    relatedCameraIds: formData.value.relatedCameraIds.map((v: any) => {
      return v.split("_")[1];
    }),
  });
  console.log("数组", formData.value.action_list);

  if (res.result == "success") {
    // formData.value.relatedCameraIds = []
    dialogVisible_add.value = false;
    //添加完成后重新获取数据
    getList(0);
    // formData.value.relatedCameraIds = []
    location.reload() 

  }
};
const openMap = () => {
  dialogVisible_map.value = true;
  setTimeout(() => {
    setMap();
  }, 100);
};
const mapClick = (event: any) => {
  let offsetX = event.offsetX;
  let offsetY = event.offsetY;
  function setMapIndex(x: number, y: number) {
    let indexPoint: any = document.querySelector(".index-point");
    indexPoint.style.top = `${y}px`;
    indexPoint.style.left = `${x}px`;
    indexPoint.style.display = `block`;
    tempIndex.value = `${x},${y}`;
  }
  setMapIndex(offsetX, offsetY);
};
const doubleclick = (event: any) => {
  isBig.value = !isBig.value;
  if (!isBig.value) {
    setMap();
    return;
  }
  let offsetX = event.offsetX;
  let offsetY = event.offsetY;
  let mapBlock: any = document.querySelector(".setMapBlock-body");
  let mapId: any = document.querySelector(".setMapBlock");
  let mapBlockHeight = mapBlock.clientHeight;
  let mapBlockWidth = mapBlock.clientWidth;
  let mapIdHeight = mapId.clientHeight;
  let mapIdWidth = mapId.clientWidth;
  let left = -event.offsetX + mapBlockWidth / 2;
  let top = -event.offsetY + mapBlockHeight / 2;
  setTimeout(() => {
    if (left > 0) left = 0;
    if (left < mapBlockWidth - mapIdWidth) left = mapBlockWidth - mapIdWidth;
    if (top > 0) top = 0;
    if (top < mapBlockHeight - mapIdHeight) top = mapBlockHeight - mapIdHeight;
    mapId.style.transform = `scale(${1})`;
    mapId.style.left = `${left}px`;
    mapId.style.top = `${top}px`;
  }, 100);
  mapId.oncontextmenu = function () {
    return false;
  };

  mapId.addEventListener("mousedown", function (event: any) {
    event.stopPropagation();
    var code = event.which;
    if (code != 3 || !isBig.value) {
      return;
    }
    let left = parseInt(mapId.style.left);
    let top = parseInt(mapId.style.top);
    let ol = event.clientX;
    let ot = event.clientY;
    document.onmousemove = function (ev) {
      let l = left + ev.clientX - ol;
      let t = top + ev.clientY - ot;
      if (l > 0) l = 0;
      if (l < mapBlockWidth - mapIdWidth) l = mapBlockWidth - mapIdWidth;
      if (t > 0) t = 0;
      if (t < mapBlockHeight - mapIdHeight) t = mapBlockHeight - mapIdHeight;
      mapId.style.left = l + "px";
      mapId.style.top = t + "px";
    };
    document.onmouseup = function () {
      document.onmousemove = null;
    };
  });
};
const setMap = () => {
  let mapBlock: any = document.querySelector(".setMapBlock-body");
  let mapId: any = document.querySelector(".setMapBlock");
  let mapBlockHeight = mapBlock.clientHeight;
  let mapBlockWidth = mapBlock.clientWidth;

  console.log("mapBlockWidth", mapBlockWidth);

  let mapIdHeight = mapId.clientHeight;
  let mapIdWidth = mapId.clientWidth;
  let zoomVal = mapBlockHeight / mapIdHeight;
  let left = (mapBlockWidth - mapIdWidth) / 2;
  let top = (mapBlockHeight - mapIdHeight) / 2;
  mapId.style.transform = `scale(${zoomVal})`;
  mapId.style.left = `${left}px`;
  mapId.style.top = `${top}px`;
  mapId.oncontextmenu = function () {
    return false;
  };
};
const setIndex = () => {
  formData.value.coordinate = tempIndex.value;
  dialogVisible_map.value = false;
  console.log("tempIndex.value", tempIndex.value);
  

};
const allDeptCameraTree = ref<any>([]);
const getAllDeptCameraTree_ = async () => {
  let res = await getAllDeptCameraTree({});
  allDeptCameraTree.value = res.data || [];
  console.log(res.data);
};
const customNodeDisabled = (data: any, node: Node) => {
  let children = data.children || [];
  if (data.type == "dept" && children.length == 0) {
    return true;
  }
};
onMounted(() => {
  let pageTable: any = document.querySelector(".page-table");
  height.value = pageTable.clientHeight;
  getList(1);
  getUser();
  getDeptInfo();
  getActionListInfo();
  getAllDeptCameraTree_();
});
</script>

<template>
  <div class="camera-page">
    <div class="page-top">
      <h4>摄像头配置</h4>
      <el-button type="primary" size="small" @click="addItem"
        >新增摄像头</el-button
      >
    </div>
    <div class="page-table">
      <el-table ref="table" v-if="height" :data="List" :height="height">
        <el-table-column label="相机编号" prop="camera_id"></el-table-column>
        <el-table-column label="相机名称" prop="camera_name"></el-table-column>
        <el-table-column label="算法" prop="action_list"></el-table-column>
        <el-table-column label="部门" prop="deptName"></el-table-column>
        <el-table-column label="ip" prop="ip"></el-table-column>
        <el-table-column label="用户名" prop="user_name"></el-table-column>
        <el-table-column label="密码" prop="password">
          <template #default="{ row }">
            <div v-if="row.passwordShow">
              <svg-icon
                icon-class="eyes2"
                @click="passwordShow(row, false)"
                style="width: 1em; height: 1em; cursor: pointer"
              ></svg-icon
              ><span>{{ row.password }}</span>
            </div>
            <div v-else>
              <svg-icon
                icon-class="eyes"
                @click="passwordShow(row, true)"
                style="width: 1em; height: 1em; cursor: pointer"
              ></svg-icon
              ><span>*****</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="坐标" prop="coordinate"></el-table-column>
        <el-table-column label="负责人" prop="userName"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button link size="small" @click="edit(row)">编辑</el-button>
            <el-button link size="small" @click="remove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-model:currentPage="currentPage"
        :page-sizes="[20, 50, 80, 100]"
        :page-size="listParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :title="isEdit ? '编辑摄像头' : '新增摄像头'"
      v-model="dialogVisible_add"
      width="440px"
    >
      <el-form ref="form" :model="formData" label-width="100px">
        <el-form-item label="相机编号" v-if="isEdit">
          <el-input
            type="number"
            disabled
            placeholder="请输入"
            v-model="formData.camera_id"
          ></el-input>
        </el-form-item>
        <el-form-item label="相机名字">
          <el-input
            type="text"
            placeholder="请输入"
            v-model="formData.camera_name"
          ></el-input>
        </el-form-item>
        <el-form-item label="算法">
          <el-select
            style="width: 100%"
            filterable
            clearable
            multiple
            v-model="formData.action_list"
            placeholder="请选择"
          >
            <el-option
              :label="c"
              :value="c"
              :key="index"
              v-for="(c, index) in actionList"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader
            style="width: 100%"
            :props="cascaderProps"
            v-model="formData.dept_id"
            :options="deptOptions"
            clearable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="ip">
          <el-input
            type="text"
            placeholder="请输入"
            v-model="formData.ip"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input
            type="text"
            placeholder="请输入"
            v-model="formData.user_name"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            type="text"
            placeholder="请输入"
            v-model="formData.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="地图坐标">
          <div class="btn-act">
            <el-input
              class="btn-input"
              type="text"
              placeholder="坐标"
              disabled
              v-model="formData.coordinate"
            ></el-input>

            <el-button class="btn" @click="openMap()" type="primary" plain
              >设置位置</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="负责人">
          <el-select
            style="width: 100%"
            v-model="formData.user_id"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              :label="u.name"
              :value="String(u.user_id)"
              v-for="(u, index) in userList"
              :key="index"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联摄像头">
          <el-tree-select
            node-key="id"
            style="width: 100%"
            filterable
            clearable
            multiple
            v-model="formData.relatedCameraIds"
            :data="allDeptCameraTree"
            :render-after-expand="false"
          ></el-tree-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible_add = false">取 消</el-button>
          <el-button type="primary" @click="confirmAdd">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置地图 -->
    <el-dialog
      :close-on-click-modal="false"
      title="提示"
      :destroy-on-close="true"
      v-model="dialogVisible_map"
      width="800"
    >
      <div class="setMapBlock-body">
        <div id="rightClickDiv">
          <div class="addProductSpan liHover">选择位置</div>
        </div>
        <div class="setMapBlock" @dblclick="doubleclick" @click="mapClick">
          <img src="@/assets/image/home/map.png" />
          <div class="index-point" style="top: 1px; left: 1px">
            <img src="@/assets/image/home/camera.png" />
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible_map = false">取 消</el-button>
          <el-button type="primary" @click="setIndex()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.camera-page {
  width: 100%;
  height: 100%;

  .page-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .page-table {
    margin: 16px 0;
    height: calc(100% - 100px);
  }
}

.setMapBlock-body {
  width: 100%;
  height: 500px;
  overflow: hidden !important;
  position: relative;
  border: 1px solid #000;
}

.setMapBlock {
  display: inline-block;
  position: absolute;
  cursor: pointer;
}

.setMapBlock .index-point {
  width: 0;
  height: 0;
  position: absolute;
  display: none;
}

.setMapBlock .index-point img {
  position: absolute;
  width: 144px;
  left: -144px;
  bottom: 0;
}

#rightClickDiv {
  display: none;
  position: fixed;
  width: 80px;
  border: 1px solid #d8d8d8;
  box-shadow: 3px 3px 5px #dadada;
  z-index: 10001;
  background-color: white;
}

#rightClickDiv > .liHover {
  position: relative;
  height: 30px;
  font-size: 16px;
  line-height: 30px;
  text-align: center;
  cursor: pointer;
}

.liHover:hover {
  /*鼠标悬浮样式*/
  background-color: #e1e1e1;
}

.btn-act {
  display: flex;

  .btn-input {
    width: 100px;
  }
}

.btn {
  margin-left: 15px;
}
</style>
